package com.czk.yygh.order.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.czk.common.rabbit.constant.RabbitConstant;
import com.czk.common.rabbit.service.RabbitService;
import com.czk.enums.OrderStatusEnum;
import com.czk.model.order.OrderInfo;
import com.czk.model.user.Patient;
import com.czk.vo.hosp.ScheduleOrderVo;
import com.czk.vo.msm.MsmVo;
import com.czk.vo.order.*;
import com.czk.yygh.common.exception.YyghException;
import com.czk.yygh.common.helper.HttpRequestHelper;
import com.czk.yygh.common.result.ResultCodeEnum;
import com.czk.yygh.hosp.client.HospitalFeignClient;
import com.czk.yygh.order.mapper.OrderMapper;
import com.czk.yygh.order.service.OrderService;
import com.czk.yygh.order.service.WeiXinService;
import com.czk.yygh.user.client.PatientFeignClient;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.DateTime;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.stream.Collectors;

/**
 * @Author:ChenZhangKun
 * @Date: 2021/11/29 15:23
 */
@Slf4j
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, OrderInfo> implements OrderService {
    @Autowired
    private PatientFeignClient patientFeignClient;
    @Autowired
    private HospitalFeignClient hospitalFeignClient;
    @Autowired
    private RabbitService rabbitService;
    @Autowired
    private WeiXinService weiXinService;

    @Override
    public Long saveOrder(String scheduleId, Long patientId) {
        // 获取就诊人信息
        Patient patient = patientFeignClient.getPatientOrder(patientId);
        // 获取排班相关信息
        ScheduleOrderVo scheduleOrderVo = hospitalFeignClient.getScheduleOrderVo(scheduleId);
        // 获取当前时间是否可以预约
        if (new DateTime(scheduleOrderVo.getStartTime()).isAfterNow()
                || new DateTime(scheduleOrderVo.getEndTime()).isBeforeNow()) {
            throw new YyghException(ResultCodeEnum.TIME_NO);
        }
        // 获取签名信息
        SignInfoVo signInfoVo = hospitalFeignClient.getSignInfoVo(scheduleOrderVo.getHoscode());
        // 添加到订单表
        OrderInfo orderInfo = new OrderInfo();
        // 拷贝信息
        BeanUtils.copyProperties(scheduleOrderVo, orderInfo);
        orderInfo.setOutTradeNo(System.currentTimeMillis() + "" + new Random().nextInt(100));
        orderInfo.setScheduleId(scheduleId);
        orderInfo.setUserId(patient.getUserId());
        orderInfo.setPatientId(patientId);
        orderInfo.setPatientName(patient.getName());
        orderInfo.setPatientPhone(patient.getPhone());
        orderInfo.setOrderStatus(OrderStatusEnum.UNPAID.getStatus());
        this.save(orderInfo);
        // 调用医院接口进行下单操作
        // 设置调用医院接口的参数
        // 调用医院接口，实现预约挂号操作
        // 设置调用医院接口需要参数，参数放到map集合
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("hoscode", orderInfo.getHoscode());
        paramMap.put("depcode", orderInfo.getDepcode());
        paramMap.put("hosScheduleId", orderInfo.getScheduleId());
        paramMap.put("reserveDate", new DateTime(orderInfo.getReserveDate()).toString("yyyy-MM-dd"));
        paramMap.put("reserveTime", orderInfo.getReserveTime());
        paramMap.put("amount", orderInfo.getAmount());

        paramMap.put("name", patient.getName());
        paramMap.put("certificatesType", patient.getCertificatesType());
        paramMap.put("certificatesNo", patient.getCertificatesNo());
        paramMap.put("sex", patient.getSex());
        paramMap.put("birthdate", patient.getBirthdate());
        paramMap.put("phone", patient.getPhone());
        paramMap.put("isMarry", patient.getIsMarry());
        paramMap.put("provinceCode", patient.getProvinceCode());
        paramMap.put("cityCode", patient.getCityCode());
        paramMap.put("districtCode", patient.getDistrictCode());
        paramMap.put("address", patient.getAddress());
        // 联系人
        paramMap.put("contactsName", patient.getContactsName());
        paramMap.put("contactsCertificatesType", patient.getContactsCertificatesType());
        paramMap.put("contactsCertificatesNo", patient.getContactsCertificatesNo());
        paramMap.put("contactsPhone", patient.getContactsPhone());
        paramMap.put("timestamp", HttpRequestHelper.getTimestamp());

        String sign = HttpRequestHelper.getSign(paramMap, signInfoVo.getSignKey());
        paramMap.put("sign", sign);
        // 请求医院系统接口
        JSONObject result = HttpRequestHelper.sendRequest(paramMap, signInfoVo.getApiUrl() + "/order/submitOrder");
        System.out.println(result);
        if (result.getInteger("code") == 200 || result.getInteger("code") == 201) {
            // 取数据
            JSONObject jsonObject = result.getJSONObject("data");
            // 预约记录唯一标识（医院预约记录主键）
            String hosRecordId = jsonObject.getString("hosRecordId");
            // 预约序号
            Integer number = jsonObject.getInteger("number");
            ;
            // 取号时间
            String fetchTime = jsonObject.getString("fetchTime");
            ;
            // 取号地址
            String fetchAddress = jsonObject.getString("fetchAddress");
            ;
            // 更新订单
            orderInfo.setHosRecordId(hosRecordId);
            orderInfo.setNumber(number);
            orderInfo.setFetchTime(fetchTime);
            orderInfo.setFetchAddress(fetchAddress);
            // 更新数据库
            baseMapper.updateById(orderInfo);
            // 排班可预约数
            Integer reservedNumber = jsonObject.getInteger("reservedNumber");
            // 排班剩余预约数
            Integer availableNumber = jsonObject.getInteger("availableNumber");
            // todo 发送消息给mq 进行号源更新和短信通知
            // 发送mq，进行号源的的更新
            OrderMqVo orderMqVo = new OrderMqVo();
            orderMqVo.setScheduleId(scheduleId);
            orderMqVo.setReservedNumber(reservedNumber);
            orderMqVo.setAvailableNumber(availableNumber);
            // 短信提示值
            MsmVo msmVo = new MsmVo();
            // 这里应该从中获取，但是容联云测试手机只能发送我的手机号
            msmVo.setPhone("15723315609");
            String reserveDate = new DateTime(orderInfo.getReserveDate()).toString("yyyy-MM-dd") + (orderInfo.getReserveTime() == 0 ? "上午" : "下午");
            Map<String, Object> map = new HashMap<String, Object>() {{
                put("title", orderInfo.getHosname() + "|" + orderInfo.getDepname() + "|" + orderInfo.getTitle());
                put("amount", orderInfo.getAmount());
                put("reserveDate", reserveDate);
                put("name", orderInfo.getPatientName());
                put("quitTime", new DateTime(orderInfo.getQuitTime()).toString("yyyy-MM-dd HH:mm"));
                put("msg", "预约成功");
            }};
            msmVo.setParam(map);
            orderMqVo.setMsmVo(msmVo);
            // 发送->医院排班接收后再向mq发送短信消息
            System.out.println("发送短信了");
            // rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_ORDER, MqConst.ROUTING_ORDER, orderMqVo);
            // 自己的方式发送mq消息
            rabbitService.sendMessage(RabbitConstant.EXCHANGE_DIRECT_ORDER, RabbitConstant.ROUTING_ORDER, orderMqVo);
        } else {
            throw new YyghException(result.getString("message"), ResultCodeEnum.FAIL.getCode());
        }
        return orderInfo.getId();
    }

    @Override
    public OrderInfo getOrders(String orderId) {
        OrderInfo orderInfo = baseMapper.selectById(orderId);
        // 设置状态码信息
        orderInfo.getParam().put("orderStatusString", OrderStatusEnum.getStatusNameByStatus(orderInfo.getOrderStatus()));
        return orderInfo;
    }

    @Override
    public IPage<OrderInfo> selectPage(Page<OrderInfo> pageParams, OrderQueryVo orderQueryVo) {
        // 医院名称
        String keyword = orderQueryVo.getKeyword();
        // 就诊人名称
        Long patientId = orderQueryVo.getPatientId();
        // 订单状态
        String orderStatus = orderQueryVo.getOrderStatus();
        // 安排时间
        String reserveDate = orderQueryVo.getReserveDate();
        // 开始时间
        String createTimeBegin = orderQueryVo.getCreateTimeBegin();
        // 结束时间
        String createTimeEnd = orderQueryVo.getCreateTimeEnd();
        //
        QueryWrapper<OrderInfo> wrapper = new QueryWrapper();
        if (!StringUtils.isEmpty(keyword)) {
            wrapper.like("hosname", keyword);
        }
        if (!StringUtils.isEmpty(patientId)) {
            wrapper.eq("patient_id", patientId);
        }
        if (!StringUtils.isEmpty(orderStatus)) {
            wrapper.eq("order_status", orderStatus);
        }
        if (!StringUtils.isEmpty(reserveDate)) {
            wrapper.eq("reserve_date", reserveDate);
        }
        if (!StringUtils.isEmpty(createTimeBegin)) {
            wrapper.ge("create_time", createTimeBegin);
        }
        if (!StringUtils.isEmpty(createTimeEnd)) {
            wrapper.le("create_time", createTimeEnd);
        }
        Page<OrderInfo> page = baseMapper.selectPage(pageParams, wrapper);
        page.getRecords().forEach(orderInfo -> {
            orderInfo.getParam().put("orderStatusString", OrderStatusEnum.getStatusNameByStatus(orderInfo.getOrderStatus()));
        });

        return page;
    }

    @Override
    public boolean cancelOrder(Long orderId) {
        // 获取订单id
        OrderInfo orderInfo = baseMapper.selectById(orderId);
        // 是否可以取消
        if (orderInfo != null && new DateTime(orderInfo.getQuitTime()).isBeforeNow()) {
            throw new YyghException(ResultCodeEnum.CANCEL_ORDER_NO);
        }
        // 调用医院接口实现取消预约
        // 调用医院接口实现预约取消
        SignInfoVo signInfoVo = hospitalFeignClient.getSignInfoVo(orderInfo.getHoscode());
        if (null == signInfoVo) {
            throw new YyghException(ResultCodeEnum.PARAM_ERROR);
        }
        Map<String, Object> reqMap = new HashMap<>();
        reqMap.put("hoscode", orderInfo.getHoscode());
        reqMap.put("hosRecordId", orderInfo.getHosRecordId());
        reqMap.put("timestamp", HttpRequestHelper.getTimestamp());
        String sign = HttpRequestHelper.getSign(reqMap, signInfoVo.getSignKey());
        reqMap.put("sign", sign);

        JSONObject result = HttpRequestHelper.sendRequest(reqMap,
                signInfoVo.getApiUrl() + "/order/updateCancelStatus");
        // 根据医院接口返回的数据进行操作
        if (result.getInteger("code") != 200) {
            throw new YyghException(result.getString("message"), ResultCodeEnum.FAIL.getCode());
        } else {
            // 判断当前订单是否可以退款
            if (orderInfo.getOrderStatus().equals(OrderStatusEnum.PAID.getStatus())) {
                // 退款
                Boolean refund = weiXinService.refund(orderId);
                if (!refund) {
                    throw new YyghException(ResultCodeEnum.CANCEL_ORDER_FAIL);
                }
                // 更新订单状态
                orderInfo.setOrderStatus(OrderStatusEnum.CANCLE.getStatus());
                baseMapper.updateById(orderInfo);
                // 号源剩余数加一
                // 发送mq
                OrderMqVo orderMqVo = new OrderMqVo();
                orderMqVo.setScheduleId(orderInfo.getScheduleId());
                //短信提示
                MsmVo msmVo = new MsmVo();
                msmVo.setPhone(orderInfo.getPatientPhone());
                String reserveDate = new DateTime(orderInfo.getReserveDate()).toString("yyyy-MM-dd") + (orderInfo.getReserveTime() == 0 ? "上午" : "下午");
                Map<String, Object> param = new HashMap<String, Object>() {{
                    put("title", orderInfo.getHosname() + "|" + orderInfo.getDepname() + "|" + orderInfo.getTitle());
                    put("reserveDate", reserveDate);
                    put("name", orderInfo.getPatientName());
                    put("msg", "取消预约成功");
                }};
                msmVo.setParam(param);
                orderMqVo.setMsmVo(msmVo);
                rabbitService.sendMessage(RabbitConstant.EXCHANGE_DIRECT_ORDER, RabbitConstant.ROUTING_ORDER, orderMqVo);
            }

        }
        return true;
    }

    /**
     * 发送就诊信息
     */
    @Override
    public void patientTips() {
        QueryWrapper<OrderInfo> wrapper = new QueryWrapper<>();
        // 拿到就诊时间
        wrapper.eq("reserve_date", new DateTime().toString("yyyy-MM-dd"));
        // 排除取消预约的订单
        wrapper.ne("order_status", OrderStatusEnum.CANCLE.getStatus());
        List<OrderInfo> orderInfos = baseMapper.selectList(wrapper);
        for (OrderInfo orderInfo : orderInfos) {
            log.info("【发送短信提醒患者就医】");
            String patientName = orderInfo.getPatientName();
            // 发送短信
            rabbitService.sendMessage(RabbitConstant.EXCHANGE_DIRECT_MSM, RabbitConstant.ROUTING_MSM_ITEM, patientName + "请及时就医哦");
        }

    }

    /**
     * 预约统计功能
     * @param orderCountQueryVo
     * @return
     */
    @Override
    public Map<String, Object> getCountMap(OrderCountQueryVo orderCountQueryVo) {
        // 得到集合
        List<OrderCountVo> orderCountVoList = baseMapper.selectOrderCountVo(orderCountQueryVo);
        // 转为日期集合
        List<String> dateList = orderCountVoList.stream().map(OrderCountVo::getReserveDate).collect(Collectors.toList());
        List<Integer> countList = orderCountVoList.stream().map(OrderCountVo::getCount).collect(Collectors.toList());
        Map<String,Object> map=new HashMap<>();
        map.put("dateList",dateList);
        map.put("countList",countList);
        return map;
    }
}
